package com.chatplus.application.controller.admin.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.basedata.MenuEntity;
import com.chatplus.application.domain.request.FiledUpdateRequest;
import com.chatplus.application.domain.request.admin.MenuSortRequest;
import com.chatplus.application.domain.response.MenuDetailResponse;
import com.chatplus.application.service.basedata.MenuService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * 前端菜单表视图控制器
 *
 * <p>Table: t_menu - 前端菜单表</p>
 *
 * @author developer
 * @see MenuEntity
 * @since 2024-04-08 10:17:35
 */
@Validated
@RestController
@RequestMapping("/api/admin/menu")
public class MenuAdminApiController {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(MenuAdminApiController.class);

    private MenuService menuService;

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @GetMapping("/list")
    public List<MenuDetailResponse> list() {
        List<MenuEntity> list = menuService.list(new LambdaQueryWrapper<MenuEntity>()
                .orderByAsc(MenuEntity::getSortNum));
        return list.stream().map(MenuDetailResponse::build).toList();
    }

    @PostMapping("/save")
    public void save(@RequestBody MenuDetailResponse menuRequest) {
        MenuEntity menuEntity = menuService.getById(menuRequest.getId());
        if (menuEntity == null) {
            menuEntity = new MenuEntity();
        }
        menuEntity.setName(menuRequest.getName());
        menuEntity.setUrl(menuRequest.getUrl());
        menuEntity.setSortNum(menuRequest.getSortNum());
        menuEntity.setEnabled(menuRequest.isEnabled());
        menuEntity.setIcon(menuRequest.getIcon());
        menuService.saveOrUpdate(menuEntity);
    }

    @PostMapping("/sort")
    public void sort(@RequestBody @Valid MenuSortRequest request) {
        if (request.getIds().size() != request.getSorts().size()) {
            throw new BadRequestException("入参格式错误");
        }
        List<MenuEntity> menuList = menuService.listByIds(request.getIds());
        if (menuList.size() != request.getSorts().size()) {
            throw new BadRequestException("菜单不存在");
        }
        for (int i = 0; i < request.getIds().size(); i++) {
            int finalIndex = i;
            Optional<MenuEntity> optional = menuList.stream()
                    .filter(menu -> menu.getId().equals(request.getIds().get(finalIndex))).findFirst();
            if (optional.isEmpty()) {
                throw new BadRequestException("菜单不存在");
            }
            MenuEntity menuEntity = optional.get();
            menuEntity.setSortNum(request.getSorts().get(finalIndex));
        }
        menuService.updateBatchById(menuList);
    }

    @GetMapping("/remove")
    @Operation(summary = "管理员删除菜单")
    public void remove(@RequestParam(value = "id") Long id) {
        menuService.removeById(id);
    }

    @PostMapping("/set")
    @Operation(summary = "管理员设置菜单状态")
    public void enable(@RequestBody FiledUpdateRequest request) {
        menuService.update(new UpdateWrapper<MenuEntity>()
                .set(request.getFiled(), Boolean.valueOf(request.getValue()))
                .eq("id", Long.valueOf(request.getId())));
    }

}
